//
//  TQQHorseCycleView.swift
//  SwiftLearning
//  跑马灯
//  Created by 黄龙 on 2024/1/24.
//

import UIKit

//跑马灯文字
class TQQHorseCycleView: UIView {

    var rollLabel:UILabel?
    
    init(frame:CGRect,title:String){
        super.init(frame: frame)
        self.initUI(title)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func initUI(_ title:String){
        self.clipsToBounds = true
        rollLabel = UILabel()
        if let rollLabel = rollLabel{
            rollLabel.font = UIFont.systemFont(ofSize: 17)
            rollLabel.text = title
            rollLabel.textColor = .label
            rollLabel.sizeToFit()
            let rollLabelMaxSize = CGSizeMake(CGFloat(MAXFLOAT), self.frame.size.height) //可以显示很长的文字
            let rollLabelSize = SwiftFunc.sizeWithText(title, font: rollLabel.font, maxSize: rollLabelMaxSize)
            NSLog("(Width=%.1f,Height=%.1f):(Width=%.1f,Height=%.1f)",rollLabel.bounds.width,rollLabel.bounds.height, rollLabelSize.width,rollLabelSize.height)
            //(554.5,20.5):(554.3,20.3),与rollLabel.bounds.size差别不大
            let rollX = self.bounds.width
            let rollY = self.bounds.height/2 - rollLabel.bounds.height/2
            rollLabel.frame = CGRectMake(rollX, rollY, rollLabel.bounds.width, rollLabel.bounds.height)
            self.addSubview(rollLabel)
        }
    }
    
    func horseRun(_ duration:CFTimeInterval){
        self.rollLabel?.layer.removeAllAnimations()
        if duration>0{
            if let rollLabel = self.rollLabel{
                let anim = CABasicAnimation(keyPath: "transform.translation.x")
                anim.toValue = -rollLabel.bounds.width - self.bounds.width
                anim.duration = duration
                anim.repeatCount = MAXFLOAT
                anim.isRemovedOnCompletion = false//没有此句切到后台动画会停止
                rollLabel.layer.add(anim, forKey: "translation")
            }
        }
    }
    
}
